let code = require('../../../constant/code');
let userInfoServices = require('../../../services/userInfoServices');
let authServices = require('../../../services/authServices');
let redisService = require('../../../services/redisService');
let pomelo = require('pomelo');
let commonDao = require('../../../dao/commonDao');
let userDao = require('../../../dao/userDao');
let logger = require('pomelo-logger').getLogger('handler');
let enumeration = require('../../../constant/enumeration');
let goldGame = require('../../../../config/goldGame');
let moment = require('moment');

let pushApi = require('../../../API/pushAPI');




module.exports = function (app) {
    return new Handler(app);
};

let Handler = function (app) {
    this.app = app;
};

//获取玩家信息
Handler.prototype.getUserInfo = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        let userData = await userDao.getUserDataByUid(session.uid);
        let updateUserData = { gold: userData.gold, goldScore: userData.goldScore };
        next(null, { code: code.OK, updateUserData, userData: userData });
    }
    catch (e) {
        logger.error(`[getUserInfo]` + e.stack);
        next(null, { code: 500 });
    }

};

//获取转盘列表
// getTurntableList  getSignList
Handler.prototype.getTurntableList = async function (msg, session, next) {

    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }

    let gift = await commonDao.findData('giftModel', {}, { 'order': 1 });
    let reward = await commonDao.findData('rewardModel', {}, { 'day': 1 });

    let dayTime = moment().format('YYYYMM');
    let playDay = moment().format('YYYYMMDD');
    let day = 0;
    let curPlay = await commonDao.findOneData('userPlayModel', { playDay, uid: session.uid });
    logger.info(`[getTurntableList]  ${session.uid} curDay = ${dayTime} curPlay = ${JSON.stringify(curPlay)} `);
    let freeDrawCount = 1;
    if (curPlay) {
        //连续天数
        day = curPlay.count;
        freeDrawCount -= (curPlay.playTime || 0);
        if (freeDrawCount <= 0) {
            freeDrawCount = 0;
        }
    }
    for (let i = 0; i < reward.length; i++) {
        let curDay = reward[i].day;
        reward[i].status = 0; //默认me
        //查询是否有奖励
        let curReward = await commonDao.findOneData('userRewardModel', { uid: session.uid, day: curDay, dayTime });
        if (curReward) {
            if (curReward.done) {
                reward[i].status = 2; //已领取
            } else {
                reward[i].status = 1; //可领取
            }
        }
    }
    let payDiamond = 20;
    next(null, { msg: { gift, reward, day, payDiamond, freeDrawCount }, code: code.OK });
}


//玩家签到
// userReward  getSignList2
Handler.prototype.userReward = async function (msg, session, next) {

    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }

    if (!msg.day) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        return;
    }

    let dayTime = moment().format('YYYYMM');
    let day = msg.day;

    let curReward = await commonDao.findOneData('userRewardModel', { uid: session.uid, day: day, dayTime, done: false });
    if (curReward) {
        let total = curReward.count;
        if (curReward.type == 1) {
            //新增钻石
            let updateUserData = { $inc: { gold: total } };
            let agentUser = await userDao.updateUserDataByUid(session.uid, updateUserData);
            logger.info(`[userPlay] get gold uid = ${session.uid} curDay = ${dayTime} total = ${total} `);
            await userInfoServices.updateUserDataNotify(session.uid, agentUser.frontendId, { gold: agentUser.gold });
            if (agentUser.frontendId) {
                let message = { awardList: [{ from: '转盘连续签到', type: 'gold', name: '钻石', count: total, message: '转盘连续签到获取奖励' }] };
                await pushApi.gameAwardPush(message, [{ uid: agentUser.uid, sid: agentUser.frontendId }])
            }
        } else if (curReward.type == 0) {

            //新增金币
            let updateUserData = { $inc: { goldScore: total } };
            let agentUser = await userDao.updateUserDataByUid(session.uid, updateUserData);
            logger.info(`[userPlay] get goldScore uid = ${session.uid} curDay = ${dayTime} total = ${total} `);
            await userInfoServices.updateUserDataNotify(session.uid, agentUser.frontendId, { goldScore: agentUser.goldScore });
            if (agentUser.frontendId) {
                let message = { awardList: [{ from: '转盘连续签到', type: 'goldScore', name: '金币', count: total, message: '转盘连续签到获取奖励' }] };
                await pushApi.gameAwardPush(message, [{ uid: agentUser.uid, sid: agentUser.frontendId }])
            }
        }
        await commonDao.findOneAndUpdate('userRewardModel', { uid: session.uid, day: day, dayTime, done: false }, { done: true });
        next(null, { code: code.OK, gold: total, type: curReward.type });
    }

}

//玩家玩转盘
//userPlay
Handler.prototype.userPlay = async function (msg, session, next) {


    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }

    let dayTime = moment().format('YYYYMM');
    let todayTime = moment().format('YYYYMMDD');
    //查询这个月是否有记录
    let curPlayRecord = await commonDao.findOneData('userPlayModel', { dayTime, uid: session.uid });
    if (!curPlayRecord) {
        // 创建每月的新记录
        let saveData = {
            dayTime,
            uid: session.uid,
            count: 1,
            playDay: todayTime,
            playTime: 0,
            createTime: Date.now(),
        };
        curPlayRecord = await commonDao.createData("userPlayModel", saveData).catch(e => { logger.error(e.stack) });
    }

    if (curPlayRecord.playDay != todayTime) {
        if (parseInt(curPlayRecord.playDay) + 1 == parseInt(todayTime)) {
            curPlayRecord = await commonDao.findOneAndUpdate('userPlayModel', { 'uid': session.uid }, { playDay: todayTime, playTime: 0, $inc: { count: 1 } });
        } else {
            curPlayRecord = await commonDao.findOneAndUpdate('userPlayModel', { 'uid': session.uid }, { count: 1, playDay: todayTime, playTime: 0 });
        }
    }

    //如果已经玩过了 需要扣钻石
    if (curPlayRecord.playDay == todayTime && curPlayRecord.playTime > 0) {
        let payDiamond = msg.payDiamond || 20;
        let agentUser = await commonDao.findOneAndUpdate('userModel', { 'uid': session.uid, gold: { '$gt': payDiamond } }, { $inc: { gold: -payDiamond } });
        if (!agentUser) {
            next(null, { code: code.NOT_ENOUGH_GOLD });
            return;
        } else {
            await userInfoServices.updateUserDataNotify(session.uid, agentUser.frontendId, { gold: agentUser.gold });
        }
    }

    let gift = await commonDao.findData('giftModel', {}, { 'order': -1 });
    let curMax = 0;
    let playList = [];
    for (let i = 0; i < gift.length; i++) {
        let { type, count, percent, order } = gift[i];
        if (percent > 0) {
            let curNum = curMax + percent * 100;
            playList.push({ type, count, percent, order, maxNum: curNum, minNum: curMax });
            curMax = curNum;
        }
    }
    // let rndNum = parseInt(Math.random() * curMax);
    let Range = playList.length - 1;
    let Rand = Math.random();
    let rndNum = Math.round(Rand * Range);
    //let curGift = playList.find(item => item.minNum <= rndNum && item.maxNum >= rndNum);
    let curGift = playList[rndNum];
    let total = (curGift && curGift.count) || 0;
    //砖石
    if (total) {
        if (curGift.type == 1) {
            //新增钻石
            let updateUserData = { $inc: { gold: total } };
            let agentUser = await userDao.updateUserDataByUid(session.uid, updateUserData);
            logger.info(`[userPlay] get gold uid = ${session.uid} curDay = ${todayTime} total = ${total} `);
            // await userInfoServices.updateUserDataNotify(session.uid, agentUser.frontendId, { gold: agentUser.gold });
            // if (agentUser.frontendId) {
            //     let message = { awardList: [{ from: '转盘', type: 'gold', name: '钻石', count: total, message: '转盘获取奖励' }] };
            //     await pushApi.gameAwardPush(message, [{ uid: agentUser.uid, sid: agentUser.frontendId }])
            // }
        } else if (curGift.type == 0) {

            //新增金币
            let updateUserData = { $inc: { goldScore: total } };
            let agentUser = await userDao.updateUserDataByUid(session.uid, updateUserData);
            logger.info(`[userPlay] get goldScore uid = ${session.uid} curDay = ${todayTime} total = ${total} `);
            // await userInfoServices.updateUserDataNotify(session.uid, agentUser.frontendId, { goldScore: agentUser.goldScore });
            // if (agentUser.frontendId) {
            //     let message = { awardList: [{ from: '转盘', type: 'goldScore', name: '金币', count: total, message: '转盘获取奖励' }] };
            //     await pushApi.gameAwardPush(message, [{ uid: agentUser.uid, sid: agentUser.frontendId }])
            // }
        }
        //更新今天玩的次数
        let curReuslt = await commonDao.findOneAndUpdate('userPlayModel', { 'uid': session.uid }, { $inc: { playTime: 1 } });
        //判断是否有联系奖励
        if (curReuslt) {
            let curReward = await commonDao.findOneData('rewardModel', { day: curReuslt.count });
            if (curReward) {
                let isHave = await commonDao.findOneData('userRewardModel', { uid: session.uid, day: curReward.day });
                if (!isHave) {
                    let saveData = {
                        dayTime,
                        uid: session.uid,
                        type: curReward.type,
                        count: curReward.count,
                        day: curReward.day,
                        done: false,
                    };
                    await commonDao.createData("userRewardModel", saveData).catch(e => { logger.error(e.stack) });
                }
            }
        }
        next(null, { code: code.OK, msg: { order: curGift.order, type: curGift.type, count: curGift.count, icon: curGift.icon } });
    }

}

//获取签到列表
Handler.prototype.getSignList = async function (msg, session, next) {

    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }
    let day = moment().format('E');
    //如果是周一 删除今天前所有数据
    let curDay = moment().weekday(1).format('YYYYMMDD');
    await commonDao.deleteData('userSignModel', { uid: session.uid, signDay: { '$lt': curDay } });
    let curSignRecord = await commonDao.findData('userSignModel', { uid: session.uid });
    let curList = await commonDao.findData('signGoldModel', {}, { day: 1 }, 0, 10);
    let signList = [];
    for (let i = 0; i < curList.length; i++) {
        let curDetail = curList[i];
        if (curDetail.day > day) {
            curDetail.isSign = -1;
        } else if (curDetail.day < day) {
            curDetail.isSign = curSignRecord.find(item => item.day == curDetail.day) ? 1 : 2;
        } else {
            curDetail.isSign = curSignRecord.find(item => item.day == curDetail.day) ? 1 : 0;
        }
        signList.push(curDetail)
    }
    next(null, { msg: { signList }, code: code.OK });
}

//玩家签到
Handler.prototype.userSign = async function (msg, session, next) {

    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }
    let day = moment().format('E');

    let curDay = moment().format('YYYYMMDD');
    //查询是否已经签过
    let curSignRecord = await commonDao.findOneData('userSignModel', { signDay: curDay, uid: session.uid });
    if (curSignRecord) {
        return next(null, { code: code.USER_SIGN_ALREADY });
    }

    let curSign = await commonDao.findOneData('signGoldModel', { day });
    let gold = (curSign && curSign.gold) || 1;
    let addGold = (curSign && curSign.addGold) || 0;

    let total = gold + addGold;

    //新增钻石
    let updateUserData = { $inc: { gold: total } };
    let agentUser = await userDao.updateUserDataByUid(session.uid, updateUserData);
    logger.info(`[userSign] uid = ${session.uid} curDay = ${curDay} total = ${total} `);
    await userInfoServices.updateUserDataNotify(session.uid, agentUser.frontendId, { gold: agentUser.gold });

    // 创建签到记录
    let saveData = {
        day: day,
        uid: session.uid,
        gold: gold,
        total: total,
        addGold: addGold,
        signDay: curDay,
        createTime: Date.now(),
    };
    await commonDao.createData("userSignModel", saveData).catch(e => { logger.error(e.stack) });

    if (agentUser.frontendId) {
        let message = { awardList: [{ from: '签到', type: 'gold', name: '钻石', count: total, message: '签到获取奖励' }] };
        await pushApi.gameAwardPush(message, [{ uid: agentUser.uid, sid: agentUser.frontendId }])
    }

    next(null, { code: code.OK, gold: total });

}

//获取金币场列表
Handler.prototype.getGoldRoom = async function (msg, session, next) {

    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        return;
    }
    let curList = [];
    for (let i = 0; i < goldGame.length; i++) {

        let { name, roomList, gameType } = goldGame[i];
        let curRoom = { name, roomList, gameType }
        if (msg.gameType) {
            if (msg.gameType == gameType) {
                curList.push(curRoom);
            }
        } else {
            curList.push(curRoom);
        }
    }
    next(null, { msg: { gameList: curList }, code: code.OK });

}

//钻石转换为金币
Handler.prototype.goldToScore = async function (msg, session, next) {


    let lockKey = session.uid + 'Score-Gold';
    let isLocked = redisService.isLocked(lockKey, 3);

    if (isLocked) {
        next(null, { code: code.USER_DATA_LOCKED });
        return;
    }

    if (!session.uid) {
        next(null, { code: code.INVALID_UERS });
        redisService.unLock(lockKey);
        return;
    }

    msg.count = parseInt(msg.count);
    if (!msg.count || typeof msg.count !== 'number' || msg.count <= 0) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        redisService.unLock(lockKey);
        return;
    }

    //用户是否存
    let userData = await userDao.getUserDataByUid(session.uid);
    if (!userData) {
        next(null, { code: code.INVALID_UERS });
        redisService.unLock(lockKey);
        return;
    }


    //砖石不足
    if (userData.gold - msg.count < 0) {
        next(null, { code: code.NOT_ENOUGH_GOLD });
        redisService.unLock(lockKey);
        return;
    }

    let config = this.app.get('config');

    let changeRate = parseInt(config['goldToScore']) || 10000;
    let score = changeRate * msg.count;

    let updateUserData = { $inc: { gold: -msg.count, goldScore: score } };
    let agentUser = await userDao.updateUserDataByUid(session.uid, updateUserData);

    await userInfoServices.updateUserDataNotify(session.uid, agentUser.frontendId, { gold: agentUser.gold, goldScore: agentUser.goldScore });

    // 创建赠送记录
    let saveData = {
        uid: agentUser.uid,
        nickname: agentUser.nickname,
        unionID: 0,
        changeCount: score,
        beforeCount: userData.goldScore || 0,
        leftCount: agentUser.goldScore,
        gameType: this.gameType,
        changeType: enumeration.scoreChangeType.EXCHANGE,
        describe: msg.count + '钻石兑换金币' + score,
        createTime: Date.now(),
    };
    await commonDao.createData("userScoreDetailModel", saveData).catch(e => { logger.error(e.stack) });
    redisService.unLock(lockKey);
    next(null, { code: code.OK });

};


Handler.prototype.transferGold = async function (msg, session, next) {


    let lockKey = session.uid + 'Add-Gold';
    let isLocked = redisService.isLocked(lockKey, 3);

    if (isLocked) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        return;
    }

    if (!session.uid || !msg.uid) {
        next(null, { code: code.INVALID_UERS });
        redisService.unLock(lockKey);
        return;
    }

    if (session.uid == msg.uid) {
        next(null, { code: code.INVALID_UERS });
        redisService.unLock(lockKey);
        return;
    }
    msg.count = parseInt(msg.count);
    if (!msg.count || typeof msg.count !== 'number' || msg.count <= 0) {
        next(null, { code: code.REQUEST_DATA_ERROR });
        redisService.unLock(lockKey);
        return;
    }

    let addUserData = await userDao.getUserDataByUid(msg.uid);
    if (!addUserData) {
        next(null, { code: code.INVALID_UERS });
        redisService.unLock(lockKey);
        return;
    }

    //用户是否存
    let userData = await userDao.getUserDataByUid(session.uid);
    if (!userData) {
        next(null, { code: code.INVALID_UERS });
        redisService.unLock(lockKey);
        return;
    }

    //是否代理
    // if (!userData.isAgent) {
    //     next(null, { code: code.PERMISSION_NOT_ENOUGH });
    //     redisService.unLock(lockKey);
    //     return;
    // }

    //砖石不足
    if (userData.gold - msg.count < 0) {
        next(null, { code: code.NOT_ENOUGH_GOLD });
        redisService.unLock(lockKey);
        return;
    }



    let updateUserData = { $inc: { gold: -msg.count } };
    let agentUser = await userDao.updateUserDataByUid(session.uid, updateUserData);

    let addUserUpdateData = { $inc: { gold: msg.count } };
    let addUser = await userDao.updateUserDataByUid(msg.uid, addUserUpdateData);

    await userInfoServices.updateUserDataNotify(session.uid, agentUser.frontendId, { gold: agentUser.gold });
    await userInfoServices.updateUserDataNotify(msg.uid, addUser.frontendId, { gold: addUser.gold });

    // 创建赠送记录
    let saveData = {
        uid: userData.uid,
        avatar: userData.avatar,
        nickname: userData.nickname,
        gainUid: addUserData.uid,
        gainName: addUserData.nickname,
        gainAvatar: addUserData.avatar,
        type: 'gold',
        count: msg.count,
        createTime: Date.now()
    };
    await commonDao.createData("adminGrantRecordModel", saveData);
    redisService.unLock(lockKey);
    next(null, { code: code.OK });

};

Handler.prototype.safeBoxOperation = async function (msg, session, next) {


    try {

        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        if (!msg.count || typeof msg.count !== 'number' || msg.count === 0) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        // 存入
        if (msg.count > 0) {
            if (userData.gold < msg.count) {
                next(null, { code: code.REQUEST_DATA_ERROR });
                return;
            }
        }
        // 取出
        else {
            if (userData.safeGold < msg.count * -1) {
                next(null, { code: code.REQUEST_DATA_ERROR });
                return;
            }
        }

        let updateUserData = {
            $inc: {
                gold: -msg.count,
                safeGold: msg.count
            }
        };
        let newUserData = await userDao.updateUserDataByUid(session.uid, updateUserData);
        if (newUserData.gold < 0 || newUserData.safeGold < 0) {
            updateUserData = {
                gold: msg.count,
                safeGold: -msg.count
            };
            await userDao.updateUserDataByUid(session.uid, updateUserData);
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        await userInfoServices.updateUserDataNotify(session.uid, newUserData.frontendId, { gold: newUserData.gold, safeGold: newUserData.safeGold });
        next(null, { code: code.OK });
    }
    catch (e) {
        logger.error(`[safeBoxOperation]` + e.stack);
        next(null, { code: 500 });
    }

};

Handler.prototype.bindPhone = async function (msg, session, next) {


    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        if (!msg.phone || !msg.smsCode) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        if (!msg.smsCode) {
            next(null, { code: code.SMS_CODE_ERROR });
            return;
        } else {
            if (!await authServices.authSmsCode(msg.phone, msg.smsCode)) {
                next(null, { code: code.SMS_CODE_ERROR });
                return;
            }
        }
        let accountData = await commonDao.findOneData("accountModel", { phoneAccount: msg.phone });
        if (!!accountData) {
            next(null, { code: code.PHONE_ALREADY_BIND });
            return;
        }

        await commonDao.updateData("accountModel", { uid: parseInt(session.uid) }, { phoneAccount: msg.phone });
        await userDao.updateUserDataByUid(session.uid, { mobilePhone: msg.phone });

        next(null, { code: code.OK, updateUserData: { mobilePhone: msg.phone } });
    }
    catch (e) {
        logger.error(`[bindPhone]` + e.stack);
        next(null, { code: 500 });
    }


};

Handler.prototype.authRealName = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        if (!msg.name || !msg.idCard) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        let realNameInfo = JSON.stringify({ name: msg.name, idCard: msg.idCard });
        let count = 1;
        let curUser = await userDao.updateUserDataByUid(session.uid, { realName: realNameInfo, $inc: { gold: count } });
        // let curUser = await userDao.updateUserDataByUid(session.uid, { realName: realNameInfo });
        if (curUser.frontendId) {
            let message = { awardList: [{ from: '实名认证', type: 'gold', name: '钻石', count: count, message: '实名认证获得奖励' }] };
            await pushApi.gameAwardPush(message, [{ uid: curUser.uid, sid: curUser.frontendId }])
        }
        next(null, { code: code.OK, updateUserData: { realName: realNameInfo, gold: curUser.gold } });
    }
    catch (e) {
        logger.error(`[authRealName]` + e.stack);
        next(null, { code: 500 });
    }


};

//更新玩家信息
Handler.prototype.updateUserInfo = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        let updateData = {};
        if (msg.avater) {
            updateData['avatar'] = msg.avater;
        }
        if (msg.nickname) {
            updateData['nickname'] = msg.nickname;
        }

        if (msg.wechatCode) {
            updateData['wechatCode'] = msg.wechatCode;
        }

        if (msg.qqCode) {
            updateData['qqCode'] = msg.qqCode;
        }

        await userDao.updateUserDataByUid(session.uid, updateData);
        let newUserData = await userDao.getUserDataByUid(session.uid);
        await userInfoServices.updateUserDataNotify(session.uid, newUserData.frontendId, updateData);
        next(null, { code: code.OK, updateUserData: updateData });
    }
    catch (e) {
        logger.error(`[updateUserInfo]` + e.stack);
        next(null, { code: 500 });
    }

};

Handler.prototype.updateUserAddress = async function (msg, session, next) {


    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        await userDao.updateUserDataByUid(session.uid, { address: msg.address, location: msg.location });

        next(null, { code: code.OK, updateUserData: { address: msg.address, location: msg.location } });
    }
    catch (e) {
        logger.error(`[updateUserAddress]` + e.stack);
        next(null, { code: 500 });
    }


};

Handler.prototype.searchByPhone = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        if (!msg.phone) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        let userData = await userDao.getUserData({ mobilePhone: msg.phone });
        if (!userData) {
            next(null, { code: code.NOT_FIND_BIND_PHONE });
        } else {
            next(null, { code: code.OK, msg: { userData: userData } });
        }
    }
    catch (e) {
        logger.error(`[searchByPhone]` + e.stack);
        next(null, { code: 500 });
    }



};

Handler.prototype.searchUserData = async function (msg, session, next) {


    try {

        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        if (!msg.uid) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        let userData = await userDao.getUserData({ uid: msg.uid });
        if (!userData) {
            next(null, { code: code.NOT_FIND_USER });
        } else {
            next(null, { code: code.OK, msg: { userData: userData } });
        }
    }
    catch (e) {
        logger.error(`[searchUserData]` + e.stack);
        next(null, { code: 500 });
    }

};

Handler.prototype.getHallNotice = async function (msg, session, next) {

    try {
        next(null, { code: code.OK, msg: { notice: [] } });
        return;
    }
    catch (e) {
        logger.error(`[getHallNotice]` + e.stack);
        next(null, { code: 500 });
    }


};

//重置密码
Handler.prototype.resetPassword = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }

        if (!msg.account || !msg.password || !msg.smsCode) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }

        if (!await authServices.authSmsCode(msg.account, msg.smsCode)) {
            res.json({ code: code.SMS_CODE_ERROR });
            return;
        }

        await commonDao.updateData("accountModel", { 'phoneAccount': msg.account, uid: parseInt(session.uid) }, { password: msg.password });
        await userDao.updateUserDataByUid(session.uid, { password: msg.password });
        next(null, { code: code.OK });
    }
    catch (e) {
        logger.error(`[resetPassword]` + e.stack);
        next(null, { code: 500 });
    }
};

//用户账号绑定
Handler.prototype.bindAccountNew = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        //
        if (!msg.account || !msg.password || !msg.smsCode) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }

        if (!await authServices.authSmsCode(msg.account, msg.smsCode)) {
            res.json({ code: code.SMS_CODE_ERROR });
            return;
        }

        let accountData = await commonDao.findOneData("accountModel", { phoneAccount: msg.account });
        if (!!accountData) {
            next(null, { code: code.ACCOUNT_EXIST });
            return;
        }

        await commonDao.updateData("accountModel", { uid: parseInt(session.uid) }, { phoneAccount: msg.account, password: msg.password });
        await userDao.updateUserDataByUid(session.uid, { account: msg.account, password: msg.password, isBind: true });
        let newUserData = await userDao.getUserDataByUid(session.uid);
        await userInfoServices.updateUserDataNotify(session.uid, newUserData.frontendId, { isBind: true, account: msg.account });
        next(null, { code: code.OK, updateUserData: { account: msg.account } });
    }
    catch (e) {
        logger.error(`[bindAccount]` + e.stack);
        next(null, { code: 500 });
    }
};

Handler.prototype.bindAccount = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        if (!msg.account || !msg.password) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        let accountData = await commonDao.findOneData("accountModel", { account: msg.account });
        if (!!accountData) {
            next(null, { code: code.ACCOUNT_EXIST });
            return;
        }

        await commonDao.updateData("accountModel", { uid: parseInt(session.uid) }, { account: msg.account, password: msg.password });
        await userDao.updateUserDataByUid(session.uid, { account: msg.account, password: msg.password, isBind: true, account: msg.account });
        let newUserData = await userDao.getUserDataByUid(session.uid);
        await userInfoServices.updateUserDataNotify(session.uid, newUserData.frontendId, { isBind: true, account: msg.account });
        next(null, { code: code.OK, updateUserData: { account: msg.account } });
    }
    catch (e) {
        logger.error(`[bindAccount]` + e.stack);
        next(null, { code: 500 });
    }
};

Handler.prototype.note = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }

        if (!msg.message || !msg.nickname) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }

        let saveData = {
            uid: session.uid,
            message: msg.message,
            contact: msg.contact || "",
            nickname: msg.nickname,
            createTime: moment().format('x')
        }

        await commonDao.createData('userNoteModel', saveData);
        next(null, { code: code.OK });
    }
    catch (e) {
        logger.error(`[note]` + e.stack);
        next(null, { code: 500 });
    }



};